Conditional Statements

  • if
  • if ... else
  • if ... [elif]* ... else # 0 or more elif statements
  • value if true else another_value

Naive initializations


In [1]:
a, b, c = 10, 15, 20
if boolean_expression:
    command0
    command1
    #...

In [2]:
if a > b:
    print('a > b')

In [3]:
if not a > b:
    print('b > a')


b > a

In [4]:
if a > b:
    print('a > b')
if boolean_expression:
    command0
    command1
    #...
else:
    command2
    command3
    #...

In [5]:
if a > b:
    print('a > b')
else:
    print('a < b')


a < b

Naive initializations


In [6]:
d, e = -1, -1
if boolean_expression:
    command0
    command1
    #...
elif: another_boolean_expression:
    command2
    command3
    #...
else:
    command4
    command5
    #...

In [7]:
if d > e:
    print('d > e')
elif e > d:
    print('e > d')
else:
    print('d == e')


d == e

'Syntactic sugar' to

if a < b and b < c:
    #...

In [8]:
if a < b < c:
    print('a < b < c')


a < b < c

In [9]:
if e < a < b < c:
    print('e < a < b < c')


e < a < b < c

In [10]:
if b > a < c:
    print('b > a < c')


b > a < c

'Ternary' statement - conditional assignment


In [11]:
x = a if a > b else b
print(x)


15

In [12]:
print('Greater of ({}, {}) -> {}'.format(a, b, a if a > b else b))


Greater of (10, 15) -> 15